package com.golden.order02.service;


import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.BufferedReader;

import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.UUID;

@Service("iDocx2PdfService")
public class IDocx2PdfServiceImpl implements IDocx2PdfService {


//	@Value("${pdf.zipCmd}")
    private String zipCmd;
    private String [] cmds = {"","",""};
    private String cmdPrefix = "";

    
    public IDocx2PdfServiceImpl() {
    	InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("applicationOrder.properties");
    	Properties pro=new Properties();
    	try {
			pro.load(inStream);
			zipCmd=pro.getProperty("pdf.zipCmd");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	
    	
        if (zipCmd == null){
            zipCmd="7z";
        }
        String os=System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")) {
            cmds[0] = "cmd";
            cmds[1] = "/C";
            cmdPrefix = "start /wait ";
        }else{
            cmds[0] = "/bin/sh";
            cmds[1] = "-c";
        }

    }

    @Override
    @Deprecated
    public String doc2PdfUtil(String documentxml) {

        String baseDir = documentxml.substring(0,documentxml.lastIndexOf('/'));


        String docx2PdfPath = baseDir + "/docx";

        return converToPdf(docx2PdfPath,documentxml,"/content.xml");
    }

    /**
     *
     * @param docxPath docx文件的路径
     * @param srcPath  替换文件的源文件
     * @param destPath 替换文件的目标文件路径。该目标文件路径为相对路径，指的是docx文件解压缩之后，相对于解压缩目录的路径。
     *                 如：使用 7z x somedocx.docx -otemp 命令中，temp为解压缩目录，目标文件路径就是要替换文件绝对路径，
     *                 去除掉的temp及temp之前的路劲所得到的路径名。如"/word/document.xml","/word/media/image1.png"等
     * @return 所生成的pdf文件，其对应的docx文件与该pdf具有相同的文件名，扩展名为docx，如：temp.pdf，那么对应的docx文件为temp.docx
     */
    @Override
    public String replaceFileInDocx(String docxPath, String srcPath, String destPath) {


        String baseDir = docxPath.substring(0,docxPath.lastIndexOf('/'));

        String dirName = baseDir + "/" + UUID.randomUUID().toString().replace("-", "");

        File dirNameFile = new File(dirName);

        cmds[2] = cmdPrefix + zipCmd + " x " + docxPath + "  -o" + dirName;

        try {
            dirNameFile.mkdir();

            Process proc = Runtime.getRuntime().exec(cmds, null, new File(baseDir));
            proc.waitFor();

        }catch (Exception e){
        }

        return converToPdf(dirName, srcPath, destPath);

    }

    private String converToPdf(String docxDir, String srtPath, String destPath){

        String outPath = docxDir.substring(0,docxDir.lastIndexOf('/')) + "/out/";

        File source = new File(srtPath);
        File dest = new File(docxDir + destPath);
        String tempFileName = UUID.randomUUID().toString().replace("-", "");
        //tempFileName = "x";
        String docxFileName = outPath + tempFileName + ".odt";
        String pdfFileName = outPath + tempFileName + ".pdf";
        try {

            FileUtils.copyFile(source, dest);
            /**
             * 用7zip命令将生成docx文件
             */
            cmds[2] = cmdPrefix + zipCmd + "  -tzip a " + docxFileName + " *";

            Process proc = Runtime.getRuntime().exec(cmds,null,new File(docxDir));
            proc.waitFor();

            /**
             * 读取执行输出结果，测试用
             */
            InputStream fis=proc.getInputStream();
            InputStreamReader isr=new InputStreamReader(fis);
            BufferedReader br=new BufferedReader(isr);
            String line=null;
            while((line=br.readLine())!=null)
            {
                System.out.println(line);
            }
            /**
             * 用soffice 命令及将docx转变为pdf文件，
             * 目前需要将soffice的路径设置在环境变量中
             */
            cmds[2] = cmdPrefix + "soffice --convert-to pdf " + docxFileName;
            proc = Runtime.getRuntime().exec(cmds,null,new File(outPath));
            proc.waitFor();

            return pdfFileName;
        } catch (Exception e) {
        }
        return null;
    }
}
